package com.cci.kangdao.controller.shankang.service.impl;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.azureAD.AzureADTool;
import com.cci.kangdao.azureBlob.AzureBlobTool;
import com.cci.kangdao.cipFleet.dto.request.CipFleetAndEsnRequest;
import com.cci.kangdao.cipFleet.entity.CipFleetT;
import com.cci.kangdao.cipFleet.service.CipFleetService;
import com.cci.kangdao.controller.shankang.dto.request.ShanKangUserRequest;
import com.cci.kangdao.controller.shankang.dto.response.ShanKangUserDisOrStartRequest;
import com.cci.kangdao.controller.shankang.dto.response.ShangKangUserResponse;
import com.cci.kangdao.controller.shankang.service.ShanKangSycMedbFleetService;
import com.cci.kangdao.controller.shankang.service.ShankangService;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.UserChannelT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.BaseResponse;
import com.cci.kangdao.dto.response.UserTResponse;
import com.cci.kangdao.externalData.service.ExternalDataSynchroService;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.service.SyncEsnAndUserId;
import com.cci.kangdao.service.impl.AKeyLoginServiceImpl;
import com.cci.kangdao.service.impl.LoginServiceImpl;
import com.cci.kangdao.utilTool.*;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: joe
 * @company: CTY
 * @since: 2024/1/18 22:13
 * @version: V1.0
 **/
@Service
public class ShankangServiceImpl implements ShankangService {

    private Logger log = Logger.getLogger(this.getClass().getName());
    @Resource
    private UserTDao userTDao;
    @Autowired
    private AKeyLoginServiceImpl aKeyLoginService;
    @Resource
    private LoginDao loginDao;
    @Resource
    private CipFleetMapper cipFleetMapper;
    @Resource
    private CustomerEngineRelDao customerEngineRelDao;
    @Resource
    private PropertiesUtils propertiesUtils;
    @Resource
    private LoginServiceImpl loginService;
    @Resource
    private UserChannelTMapper userChannelTMapper;
    @Resource
    private ExternalDataSynchroService externalDataSynchroService;
    @Resource
    private SyncEsnAndUserId syncEsnAndUserId;
    @Resource
    private CipFleetService cipFleetService;
    @Resource
    private ShanKangSycMedbFleetService shanKangSycMedbFleetService;

    @Value("${accountName}")
    private String azureAccount;
    @Value("${blobConnection}")
    private String blobConnection;
    @Value("${containerName}")
    private String containerName;

    private Pattern WWID_PATTERN = Pattern.compile("^([A-Za-z]{2})([0-9A-Za-z]{3})$");
    /**
     * 验证用户
     * @param list
     * @return
     */
    public String verifyUser(List<ShanKangUserRequest> list){
        if (CollectionUtils.isEmpty(list)) {
            return "用户不能为空";
        }
        boolean phonFlag = list.stream().anyMatch(e -> StringUtils.isBlank(e.getPhone()));
        if (phonFlag) {
            return "手机号不能为空";
        }
        boolean externalFlag = list.stream().anyMatch(e -> StringUtils.isBlank(e.getExternalUserId()));
        if (externalFlag) {
            return "用户id不能为空";
        }
        return null;
    }
    /**
     * 保存用户
     * @param userStr
     * @param request
     * @param response
     * @return
     */
    @Override
    public BaseResponse saveUser(String userStr, HttpServletRequest request, HttpServletResponse response) {
        List<ShanKangUserRequest> userTS = JSON.parseArray(userStr, ShanKangUserRequest.class);
        String resultStr = this.verifyUser(userTS);
        if (StringUtils.isNotBlank(resultStr)) {
            return BaseResponse.error(resultStr);
        }
        List<ShangKangUserResponse> successList = new ArrayList<>();
        List<ShangKangUserResponse> failList = new ArrayList<>();
        for (ShanKangUserRequest userInfo : userTS) {
            //添加用户
            ShangKangUserResponse userResponse = this.addUser(userInfo);
            if(userResponse.getStatus() == 0){
                successList.add(userResponse);
            } else {
                failList.add(userResponse);
            }
        }

        Map<String,Object> map = new HashMap<>();
        map.put("successList",successList);
        map.put("failList",failList);
        return BaseResponse.success(map);
    }
    public List<ShangKangUserResponse> getUserFailVoList(List<UserTResponse> userTList){
        List<ShangKangUserResponse> listVo = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userTList)) {
            ShangKangUserResponse shangKangUserResponse;
            for (UserTResponse userT : userTList) {
                shangKangUserResponse = new ShangKangUserResponse();
                shangKangUserResponse.setUserId(userT.getId());
                shangKangUserResponse.setExternalUserId(userT.getExternalUserId());
                shangKangUserResponse.setMessage(userT.getMessage());
                listVo.add(shangKangUserResponse);
            }
        }
        return listVo;
    }
    public List<ShangKangUserResponse> getUserSuccessVoList(List<UserT> userTList){
        List<ShangKangUserResponse> listVo = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userTList)) {
            ShangKangUserResponse shangKangUserResponse;
            for (UserT userT : userTList) {
                shangKangUserResponse = new ShangKangUserResponse();
                shangKangUserResponse.setUserId(userT.getId());
                shangKangUserResponse.setExternalUserId(userT.getExternalUserId());
                listVo.add(shangKangUserResponse);
            }
        }
        return listVo;
    }

    public ShangKangUserResponse addUser(ShanKangUserRequest userInfo){
        String regex = "^([A-Za-z]{2})([0-9A-Za-z]{3})$";
        ShangKangUserResponse userResponse = new ShangKangUserResponse();
        userResponse.setExternalUserId(userInfo.getExternalUserId());
        UserT userT = userTDao.getUserByPhone(userInfo.getPhone());
        //wwid用户
        if(StringUtils.isNotBlank(userInfo.getUserName()) && userInfo.getUserName().matches(regex)){
            UserT userWWidT = userTDao.getUserByWWid(userInfo.getUserName());
            //根据手机号没有用户 根据wwid 查找到用户
            if(null == userT && null != userWWidT){
                userT = userWWidT;
            }
            //根据手机号查找到用户 根据wwid 查找到用户
            if(null != userT && null != userWWidT){
                if(userT.getId() != userWWidT.getId()){
                    userResponse.setMessage("wwid用户和手机号不一致，请自行修改");
                    userResponse.setStatus(-98);
                }
            }
            //手机号用户是另一个wwid
            if(null != userT && null == userWWidT && !userT.getUserName().equals(userInfo.getUserName()) && userT.getType() == 2){
                userResponse.setMessage("wwid用户和手机号不一致，请自行修改");
                userResponse.setStatus(-98);
            }
        } else {
            if(null != userT){
                //是否为终端用户
                int i = userTDao.isEndUser(userT.getId());
                if (i <= 0) {
                    userResponse.setMessage("非终端用户,不可同步");
                    userResponse.setStatus(-96);
                }
            }
        }
        if(null != userT){
            List<UserChannelT> channelList = userChannelTMapper.getUserChannelListByUserId(userT.getId());
            if(CollectionUtils.isNotEmpty(channelList)) {
                List<String> channelNoList = channelList.stream().map(UserChannelT::getServiceChannel).filter(a -> StringUtils.isNotBlank(a)).collect(Collectors.toList());
                if (!channelNoList.contains("4")) {
                    userResponse.setMessage("其他渠道账号不允许同步");
                    userResponse.setStatus(-95);
                }
            }
        }
        if(userResponse.getStatus() == 0){
            if (null != userT) {
                userResponse.setUserId(userT.getId());
                //wwid用户
                if(StringUtils.isNotBlank(userInfo.getUserName())
                        && userInfo.getUserName().matches(regex)){
                    userT.setShankangWWID(userInfo.getUserName());
                    if(userT.getType() == 1){
                        // 该员工编号在AD用户池
                        String adUserId = getAdUserIdByEmployeeNum(userInfo.getUserName());
                        if (StringUtils.isNotEmpty(adUserId)) {
                            UserT existUser = loginDao.getUserByUserName(userInfo.getUserName());
                            UserT adUser = loginDao.getUserByAdUserId(adUserId);
                            // 判断可否绑定
                            Boolean canBind = Boolean.FALSE;
                            // 该员工编号在数据库中不存在可以绑定
                            if(null == existUser && null == adUser){
                                canBind = Boolean.TRUE;
                            }else{
                                // 该员工编号在数据库存在，但是是当前用户可以绑定
                                if(null != existUser && existUser.getId() == userT.getId()){
                                    canBind = Boolean.TRUE;
                                }
                            }
                            if (canBind) {
                                userT.setAduserId(adUserId);
                                userT.setUserName(userInfo.getUserName());
                                userT.setType(2);
                                userT.setEmployeeNum(userInfo.getUserName());
                                userTDao.updateByPrimaryKeySelective(userT);
                            }
                        }
                    }
                }
                userT.setPhone(userInfo.getPhone());
                userT.setContact(userInfo.getContact());
                userT.setEmail(userInfo.getEmail());
                userT.setSex(userInfo.getSex());
                userTDao.updateUserMsgById(userT);
            } else {
                //注册用户
                userT = new UserT();
                userT.setPhone(userInfo.getPhone());
                userT.setContact(userInfo.getContact());
                userT.setUserSource(6);// 6为陕康云
                userT.setEmail(userInfo.getEmail());
                userT.setSex(userInfo.getSex());
                String userName = userInfo.getPhone();
                if(StringUtils.isNotBlank(userInfo.getUserName())){
                    if (userInfo.getUserName().matches(regex)) {
                        userT.setShankangWWID(userInfo.getUserName());
                        userName = userInfo.getUserName();
                    }
                }
                userT.setUserName(userName);
                Long userId = externalDataSynchroService.registerEndUser(userT);
                if(null != userId){
                    userT.setId(userId);
                    userResponse.setUserId(userId);
                } else {
                    userResponse.setMessage("注册失败，请联系管理员");
                    userResponse.setStatus(-97);
                }
            }
        }
        if(userResponse.getStatus() == 0 && null != userResponse.getUserId()){
            Long oldUserId = userChannelTMapper.getUserChannelByExternalUserIdAndChannel(userInfo.getExternalUserId(), "4");
            if(null != oldUserId && !oldUserId.equals(userResponse.getUserId())){
                UserT oldUser = userTDao.selectById(oldUserId);
                if(null != oldUser){
                    //同步删除原账号cip车辆
                    syncEsnAndUserId.asSyncEsnAndUserIdDelByuserId(oldUserId);
                    userChannelTMapper.delete(oldUserId, "4", LocalTimeUtil.getRealCurrentTime());
                    //去除  shankang 的wwid
                    UserT user = new UserT();
                    user.setId(oldUserId);
                    user.setShankangWWID("");
                    userTDao.updateUserMsgById(user);
                    //同步重新添加cip车辆
                    syncEsnAndUserId.asSyncEsnAndUserIdAddByuserId(oldUserId);
                }

                UserChannelT userChannel = userChannelTMapper.getUserChannelByUserIdAndChannel(userResponse.getUserId(), "4");
                if(null == userChannel){
                    UserChannelT userChannelT = new UserChannelT();
                    userChannelT.setCreator(userResponse.getUserId());
                    userChannelT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                    userChannelT.setUserId(userResponse.getUserId());
                    userChannelT.setServiceChannel("4");
                    userChannelT.setExternalUserId(userResponse.getExternalUserId());
                    userChannelTMapper.insert(userChannelT);
                } else {
                    userChannel.setExternalUserId(userInfo.getExternalUserId());
                    userChannel.setUpdator(userResponse.getUserId());
                    userChannel.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                    userChannelTMapper.update(userChannel);
                }

                if(null != oldUser){
                    //将之前用的绑车信息重新同步到新账号
                    List<Map<String, Object>> listMapByUserId = customerEngineRelDao.getListMapByUserId(oldUserId);
                    if (CollectionUtils.isNotEmpty(listMapByUserId)) {
                        for (Map<String, Object> customerEngineRelT : listMapByUserId) {
                            customerEngineRelT.put("ID", null);
                            customerEngineRelT.put("UserId", userResponse.getUserId());
                            customerEngineRelT.put("Creator", userResponse.getUserId());
                            customerEngineRelT.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
                            customerEngineRelT.put("Updator", userResponse.getUserId());
                            customerEngineRelT.put("UpdateTime", LocalTimeUtil.getRealCurrentTime());
                            customerEngineRelDao.newAddCustomerEngineRel(customerEngineRelT);
                        }
                    }
                    //将新加的数据同步到cip
                    syncEsnAndUserId.asSyncEsnAndUserIdAddByuserId(userResponse.getUserId());
                    //修改车队删除外部id
                    cipFleetService.updateFleetByUserId(oldUserId, userResponse.getUserId(),userInfo.getExternalUserId(),4);
                    //修改vip用户
                    userTDao.updateVehicleByUserId(oldUserId,userResponse.getUserId());
                    userTDao.updateToSharedByUserId(oldUserId,userResponse.getUserId(),userT.getUserName(),userT.getPhone());
                    userTDao.updateSharedByUserId(oldUserId,userResponse.getUserId());
                }
            }
            UserChannelT userChannel = userChannelTMapper.getUserChannelByUserIdAndChannel(userResponse.getUserId(), "4");
            if(null == oldUserId){
                //同步删除原账号cip车辆
                syncEsnAndUserId.asSyncEsnAndUserIdDelByuserId(userResponse.getUserId());
                if(null == userChannel){
                    UserChannelT userChannelT = new UserChannelT();
                    userChannelT.setCreator(userResponse.getUserId());
                    userChannelT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                    userChannelT.setUserId(userResponse.getUserId());
                    userChannelT.setServiceChannel("4");
                    userChannelT.setExternalUserId(userResponse.getExternalUserId());
                    userChannelTMapper.insert(userChannelT);
                } else {
                    userChannel.setExternalUserId(userInfo.getExternalUserId());
                    userChannel.setUpdator(userResponse.getUserId());
                    userChannel.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                    userChannelTMapper.update(userChannel);
                }
                //同步添加新账号cip车辆
                syncEsnAndUserId.asSyncEsnAndUserIdAddByuserId(userResponse.getUserId());
                //修改车队
                cipFleetService.updateFleetListByUserId(userResponse.getUserId());
            }

        }
        return userResponse;
    }
    /**
     * 更新用户集合
     * @param usersUpdateChannel
     * @param users
     * @return
     */
    public List<UserTResponse> updateUserlIist(List<UserT> usersUpdateChannel,List<UserT> users){
        List<UserTResponse> failList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(users)) {
            UserTResponse failUser = new UserTResponse();
            for (UserT ut : users) {
                try {
                    failUser = new UserTResponse();
                    BeanUtils.copy(ut, failUser);
                    //同步删除原账号cip车辆
                    syncEsnAndUserId.asSyncEsnAndUserIdDelByuserId(ut.getId());
                    userChannelTMapper.delete(ut.getId(),"4",LocalTimeUtil.getRealCurrentTime());
                    //同步添加新账号cip车辆
                    syncEsnAndUserId.asSyncEsnAndUserIdAddByuserId(ut.getId());
                    //修改车队
                    cipFleetService.updateFleetListByUserId(ut.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                    failUser.setMessage(e.getMessage());
                    failList.add(failUser);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(usersUpdateChannel)) {
            UserTResponse failUser = new UserTResponse();
            for (UserT ut : usersUpdateChannel) {
                try {
                    BeanUtils.copy(ut, failUser);
                    UserChannelT channelT = userChannelTMapper.getUserChannelByUserIdAndChannel(ut.getId(),"4");
                    if(null == channelT){
                        UserChannelT userChannelT = new UserChannelT();
                        userChannelT.setCreator(ut.getId());
                        userChannelT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                        userChannelT.setUserId(ut.getId());
                        userChannelT.setServiceChannel("4");
                        userChannelT.setExternalUserId(ut.getExternalUserId());
                        userChannelTMapper.insert(userChannelT);
                    }
                } catch (Exception e) {
                    failUser.setMessage(e.getMessage());
                    failList.add(failUser);
                }
            }
        }
        return failList;
    }

    /**
     * 添加新的用户集合
     * @param users
     * @return
     */
    public List<UserTResponse> saveUserlIist(List<UserT> users){
        List<UserTResponse> failList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(users)) {
            UserTResponse failUser = new UserTResponse();

            for (UserT ut : users) {
                try {
                    failUser = new UserTResponse();
                    BeanUtils.copy(ut, failUser);
                    ut.setFlag(0);
                    ut.setSystime(LocalTimeUtil.getRealCurrentTime());
                    if (StringUtils.isNotBlank(ut.getUserName())) {
                        if (ut.getUserName().length()>5) {
                            ut.setUserName(null);
                        }else {
                            String regex = "^[A-Za-z]{2}\\d{3}$";
                            if (ut.getUserName().matches(regex)) {
                                ut.setShankangWWID(ut.getUserName());
                            }
                        }
                    }
                    ut.setUserName(ut.getPhone());
                    if (StringUtils.isBlank(ut.getContact())) {
                        ut.setContact(ut.getPhone());
                    }
                    ut.setUserSource(6);// 6为陕康云
                    if (StringUtils.isBlank(ut.getContact())) {
                        ut.setContact(ut.getPhone());
                    }
                    Long userId = externalDataSynchroService.registerEndUser(ut);
                    if (null == userId) {
                        failUser.setMessage("注册失败，请联系管理员");
                        failList.add(failUser);
                    } else {
                        if (StringUtils.isNotBlank(ut.getShankangWWID())) {
                            UserT user = new UserT();
                            user.setId(userId);
                            user.setShankangWWID(ut.getShankangWWID());
                            userTDao.updateUserMsgById(user);
                        }
                        UserChannelT userChannelT = new UserChannelT();
                        userChannelT.setCreator(userId);
                        userChannelT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                        userChannelT.setUserId(userId);
                        userChannelT.setServiceChannel("4");
                        userChannelT.setExternalUserId(ut.getExternalUserId());
                        userChannelTMapper.insert(userChannelT);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    failUser.setMessage(e.getMessage());
                    failList.add(failUser);
                }
            }
        }
        return failList;
    }

    @Override
    public BaseResponse disableOrStartUser(String cipFleetStr, HttpServletResponse response) {
        ShanKangUserDisOrStartRequest convert = JSON.parseObject(cipFleetStr,ShanKangUserDisOrStartRequest.class);
        if (StringUtils.isBlank(convert.getPhone())) {
            return BaseResponse.error("用户手机号必传");
        }
        if (null==convert.getDisableFlag()) {
            return BaseResponse.error("开启还是关闭必传");
        }

        UserT userTByUserName = userTDao.getUserByPhone(convert.getPhone());
        if (userTByUserName==null) {
            return BaseResponse.error("用户手机号不存在");
        }
        List<UserChannelT> channelList = userChannelTMapper.getUserChannelListByUserId(userTByUserName.getId());
        if(CollectionUtils.isNotEmpty(channelList)) {
            List<String> channelNoList = channelList.stream().map(UserChannelT::getServiceChannel).filter(a -> StringUtils.isNotBlank(a)).collect(Collectors.toList());
            if (!channelNoList.contains("4")) {
                return BaseResponse.error("非陕康云用户");
            }
        }
        if (!convert.getDisableFlag()) {
            //删除该用户下  陕康云的 设备  和  车队
            //同步删除 cip数据 设备
            syncEsnAndUserId.asSyncEsnAndUserIdDelByuserId(userTByUserName.getId());
            //同步删除 cip数据 车队
            cipFleetService.appDeleteFleetByUserIdAndChannel(userTByUserName.getId(),"4");
            customerEngineRelDao.deleteEngineRelShanKangByUserId(userTByUserName.getId(), LocalTimeUtil.getRealCurrentTime());
            userChannelTMapper.delete(userTByUserName.getId(), "4", LocalTimeUtil.getRealCurrentTime());
            //去除  shankang 的wwid
            UserT user = new UserT();
            user.setId(userTByUserName.getId());
            user.setShankangWWID("");
            userTDao.updateUserMsgById(user);
            //同步添加新账号cip车辆
            syncEsnAndUserId.asSyncEsnAndUserIdAddByuserId(userTByUserName.getId());
            //修改车队
            cipFleetService.updateFleetListByUserId(userTByUserName.getId());
            //删除medb 车队
            List<CipFleetT> fleetTList = cipFleetMapper.getListByUserId(userTByUserName.getId());
            for(CipFleetT updateFleetT : fleetTList){
                if (StringUtils.isNotBlank(updateFleetT.getServiceChannel()) && updateFleetT.getServiceChannel().equals("4")) {
                    //删除车队同步cip
                    shanKangSycMedbFleetService.sycdeleteMedbFleet(updateFleetT.getExternalFleetId(),userTByUserName.getShankangWWID());

                }
            }

        } else {
            //同步删除陕康云车辆
            syncEsnAndUserId.asSyncEsnAndUserIdDelByuserIdChannel(userTByUserName.getId(),"4");
            customerEngineRelDao.deleteEngineRelShanKangByUserId(userTByUserName.getId(), LocalTimeUtil.getRealCurrentTime());
        }
        //开启需要 陕康云同步设备和车队的功能
        return BaseResponse.success();
    }

    /**
     * 修改用户信息   手机号（必须有值，陕康云改成必填）、用户昵称、性别、邮箱）
     *
     * @param userStr
     * @param response
     * @return
     */
    @Override
    public BaseResponse updateUser(String userStr, HttpServletResponse response,HttpServletRequest request) {
        ShanKangUserRequest shanKangUserRequest = JSON.parseObject(userStr, ShanKangUserRequest.class);
        if (StringUtils.isBlank(shanKangUserRequest.getPhone())) {
            return BaseResponse.error("手机号不能为空");
        }
        if (StringUtils.isNotBlank(shanKangUserRequest.getOldPhone())) {
            if (!shanKangUserRequest.getPhone().equals(shanKangUserRequest.getOldPhone())) {
                UserT userByPhone = userTDao.getUserByPhone(shanKangUserRequest.getPhone());
                if (userByPhone != null ) {
                    return BaseResponse.error("手机号已经存在，不允许修改手机号");
                }else {
                    //之前的账号保留 去除 陕康云的标识
                    Long oldUserId = userChannelTMapper.getUserChannelByExternalUserIdAndChannel(shanKangUserRequest.getExternalUserId(),"4");
                    //注册新的账号
                    ShangKangUserResponse userResponse = this.addUser(shanKangUserRequest);
                    if(userResponse.getStatus() != 0){
                        return BaseResponse.error(userResponse.getMessage());
                    }
                    Map<String, Object> data = new HashMap<>();
                    data.put("userId",userResponse.getUserId());
                    return BaseResponse.success(data);
                }
            }
        }
        //注册新的账号
        ShangKangUserResponse userResponse = this.addUser(shanKangUserRequest);
        if(userResponse.getStatus() != 0){
            return BaseResponse.error(userResponse.getMessage());
        }else {
            Map<String, Object> data = new HashMap<>();
            data.put("userId",userResponse.getUserId());
            return BaseResponse.success(data);
        }
    }

    public void  syncEsnAndFleet(Long oldUserId,UserT userT) {
        if(null != oldUserId){
            //将之前用的绑车信息重新同步到新账号
            List<Map<String, Object>> listMapByUserId = customerEngineRelDao.getListMapByUserId(oldUserId);
            if (CollectionUtils.isNotEmpty(listMapByUserId)) {
                for (Map<String, Object> customerEngineRelT : listMapByUserId) {
                    customerEngineRelT.put("ID", null);
                    customerEngineRelT.put("UserId", userT.getId());
                    customerEngineRelT.put("Creator", userT.getId());
                    customerEngineRelT.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
                    customerEngineRelT.put("Updator", userT.getId());
                    customerEngineRelT.put("UpdateTime", LocalTimeUtil.getRealCurrentTime());
                    customerEngineRelDao.newAddCustomerEngineRel(customerEngineRelT);
                }
            }
        }

        //将新加的数据同步到cip
        syncEsnAndUserId.asSyncEsnAndUserIdAddByuserId(userT.getId());
        if(null != oldUserId){
            //修改车队删除外部id
            cipFleetService.updateFleetByUserId(oldUserId,userT.getId(),userT.getExternalUserId(),4);

        }
    }

    public boolean registerEndUser(UserT userT,HttpServletRequest request,HttpServletResponse response){
        userT.setUserSource(6);// 6为陕康云
        String ip = RequestIPUtils.getRequestClientRealIp(request);
        //通过IP获取 地区
        userT = GDRegion.addProviceAndCity(ip, userT);
        userT.setServiceChannel("4");
        boolean isSuccess = aKeyLoginService.registerEndUser(response, userT);
        if (StringUtils.isBlank(userT.getUserName()) && StringUtils.isNotBlank(userT.getPhone())) {
            //更新密码
            JSONObject jsonObjectUpdate = new JSONObject();
            jsonObjectUpdate.put("userId", userT.getId());
            jsonObjectUpdate.put("passwork", NumberUtils.getStringRandom(8));
            updateUserWord(jsonObjectUpdate.toString());
        }
       return isSuccess;
    }

    public BaseResponse updateUserWord(String userStr) {
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(userStr);
        Long id = jsonObject.getLong("userId");
        String pass = jsonObject.getString("password");
        if (StringUtils.isBlank(pass)) {
            return BaseResponse.error("请输入用户密码");
        }
        //解密
        pass = AESTool.decryptString(pass);
        if (null == id) {
            return BaseResponse.error("请输入用户id");
        }
        UserT userByPhone = loginDao.getUserByUserId(id);
        if (null == userByPhone) {
            return BaseResponse.error("手机号错误");
        }
        if (pass.contains(userByPhone.getUserName())) {
            return BaseResponse.error(2, "您好，您输入的密码不能包含用户名信息，请修改");
        }

        //=============================================更新AD池里的用户密码============================================
        //连接AD
        String AUTHORITY = this.propertiesUtils.getPropertiesValue("authority");
        String RESOURCE = this.propertiesUtils.getPropertiesValue("resource");
        String webClient_id = this.propertiesUtils.getPropertiesValue("webClient_id");
        String webClientSecret = this.propertiesUtils.getPropertiesValue("webClientSecret");
        String tenant = this.propertiesUtils.getPropertiesValue("tenant");
        //获取token
        AUTHORITY = AUTHORITY.replace("common", tenant);
        IAuthenticationResult result = AzureADTool.getAccessTokenByClient(webClient_id, webClientSecret, AUTHORITY, RESOURCE);
        if (result == null) {
            return BaseResponse.error("添加失败，请联系管理员");
        }
        //修改密码
        boolean flag = AzureADTool.chagePasswordAzureUser(userByPhone.getAduserId(), pass, result.accessToken(), tenant);
        //远程刷新token
        String username = userByPhone.getUserName() + "@" + tenant;
        String token = loginService.remoteInitToken(username, pass);
        return BaseResponse.success();
    }

    /**
     * 上传文件维护车辆
     * @return
     * @throws IOException
     */
    @Override
    public BaseResponse upholdVehicles(MultipartFile file) throws IOException {
        if(null == file){
            return BaseResponse.error("未发现文件！");
        }
        InputStream is = file.getInputStream();
        Workbook wb = new XSSFWorkbook(is);
        //默认第一个sheet页
        Sheet sheet = wb.getSheetAt(0);
        if (null == sheet) {
            return BaseResponse.error("数据为空，请检查文件！");
        }
        if (sheet.getLastRowNum() == 0 || sheet.getPhysicalNumberOfRows() == 0) {
            return BaseResponse.error("数据为空，请检查文件！");
        }
        String name = "skyUpholdVehicles-" + System.currentTimeMillis() + PublicTool.getFourRandom();
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "template";
        File imgFile = new File(path);
        if(!imgFile.exists()){
            imgFile.mkdirs();
        }
        String fileName = path + "/" + name + ".xlsx";
        File newFile = new File(fileName);
        FileOutputStream outputStream = new FileOutputStream(newFile);
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        workbook.write(outputStream);

        String filename = AzureBlobTool.uploadBlob(azureAccount, blobConnection, containerName, fileName);
        log.info("同步陕康云esn保存文件名:" + filename);
        customerEngineRelDao.addSkyVehiclesFile(filename,LocalTimeUtil.getRealCurrentTime());

        Map<String,Object> returnMap = new HashMap<>();
        return BaseResponse.success(returnMap);
    }

    public String  verifyCipfleet(List<CipFleetAndEsnRequest> cipFleetAndEsnRequests){
        //用户不能为空
        boolean userFlag = cipFleetAndEsnRequests.stream().anyMatch(cipFleetAndEsn -> null == cipFleetAndEsn.getUserId());
        if (userFlag) {
            return "用户id不能为空";
        }
        //渠道分类不能为空
        boolean channelFlag = cipFleetAndEsnRequests.stream().anyMatch(cipFleetAndEsn -> StringUtils.isBlank(cipFleetAndEsn.getServiceChannel()));
        if (channelFlag) {
            return "渠道不能为空";
        }
        //车队名称分类不能为空
        boolean nameFlag = cipFleetAndEsnRequests.stream().anyMatch(cipFleetAndEsn -> StringUtils.isBlank(cipFleetAndEsn.getFleetName()));
        if (nameFlag) {
            return "名称不能为空";
        }
        //去重
        cipFleetAndEsnRequests = cipFleetAndEsnRequests.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p -> p.getUserId() + "-" + p.getFleetName()))), ArrayList::new));
        //车队名称分类不能为空
        List<String> userIdAndFleetList = cipFleetAndEsnRequests.stream().map(cipFleet -> cipFleet.getUserId() + "-" + cipFleet.getFleetName()).collect(Collectors.toList());
        int count = cipFleetMapper.getListByUserIdAndFleet(userIdAndFleetList);
        if (count > 0) {
            return "用户之前创建过车队";
        }
        return null;
    }

    private String getAdUserIdByEmployeeNum(String employeeNum) {
        String adUserId = null;
        if (StringUtils.isNotEmpty(employeeNum) && WWID_PATTERN.matcher(employeeNum).matches()) {
            String webClientId = this.propertiesUtils.getPropertiesValue("webClient_id");
            String webClientSecret = this.propertiesUtils.getPropertiesValue("webClientSecret");
            String tenant = this.propertiesUtils.getPropertiesValue("tenant");
            String innerTenant = this.propertiesUtils.getPropertiesValue("innerTenant");
            //获取token
            String token = AzureADTool.getManagementToken(tenant, webClientId, webClientSecret);
            //查询用户信息
            String userJson = AzureADTool.getUser(employeeNum, innerTenant, token);
            //用户存在，说明该用户为内部用户
            if (StringUtils.isNotEmpty(userJson)) {
                Map<String, Object> userMap = JsonUtils.toJavaObject(userJson, Map.class);
                adUserId = (String) userMap.get("id");
            }
        }
        return adUserId;
    }
}
